using APP.HELPER.Data.Helper;
using APP.HELPER.Utils.Language;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using Extra.Data.Extra.Class;
using Extra.ERP;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.VisualBasic;
using System;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Windows.Forms;
namespace Extra.Data.Extra.Forms
{
    public class XfmBackupDatabase : XtraForm
    {
        private ProgressBarControl Bar;
        private SimpleButton btnClose;
        private SimpleButton btnHelp;
        private SimpleButton btnStart;
        private CheckEdit cheOverwrite;
        private IContainer components = null;
        private GroupControl groupControl1;
        private LabelControl lblDetail;
        private LabelControl lblFileName;
        private LabelControl lblMessage;
        private LabelControl lblPath;
        private LabelControl lblProgress;
        private PictureBox pictureBox1;
        private TextEdit txtBackupFile;
        private ButtonEdit txtBackupFolder;

        public event BackupCompleteEventHander BackupComplete;

        public event BackupErrorEventHander BackupError;

        public event BackupProcessEventHander BackupProcess;

        public event ClosedHandler Closed;

        public XfmBackupDatabase()
        {
            this.InitializeComponent();
            this.InitMultiLanguages();
            this.txtBackupFolder.Text = LoadPath();
            SqlHelper helper = new SqlHelper(SqlHelper.ConnectString);
            helper.Extract();
            this.txtBackupFile.Text = helper.Database + "." + Strings.Format(DateTime.Now, "dd.MM.yy hh.mm.bak");
        }

        private void BackupBackupComplete(object sender, ServerMessageEventArgs e)
        {
            if (this.Bar.InvokeRequired)
            {
                BackupCompleteEventHander method = new BackupCompleteEventHander(this.BackupBackupComplete);
                base.Invoke(method, new object[] { sender, e });
            }
            else
            {
                this.Bar.EditValue = 0;
                this.btnStart.Enabled = true;
                this.lblMessage.Text = "Sao Lưu Th\x00e0nh C\x00f4ng";
            }
            this.RaiseBackupCompleteEventHander(e);
        }

        private void BackupBackupError(object sender, string message)
        {
            if (this.Bar.InvokeRequired)
            {
                BackupErrorEventHander method = new BackupErrorEventHander(this.BackupBackupError);
                base.Invoke(method, new object[] { sender, message });
            }
            else
            {
                XtraMessageBox.Show("Error:\n\t" + message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                this.btnStart.Enabled = true;
            }
            this.RaiseBackupErrorEventHander(message);
        }

        private void BackupBackupProcess(object sender, PercentCompleteEventArgs e)
        {
            if (this.Bar.InvokeRequired)
            {
                BackupProcessEventHander method = new BackupProcessEventHander(this.BackupBackupProcess);
                base.Invoke(method, new object[] { sender, e });
            }
            else
            {
                this.Bar.EditValue = e.Percent;
            }
            this.RaiseBackupProcessEventHander(e);
        }

        private void BtnCloseClick(object sender, EventArgs e)
        {
            base.Close();
        }

        private void BtnPathClick(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                this.txtBackupFolder.Text = dialog.SelectedPath;
            }
        }

        private void BtnStartClick(object sender, EventArgs e)
        {
            if (!Directory.Exists(this.txtBackupFolder.Text))
            {
                Directory.CreateDirectory(this.txtBackupFolder.Text);
                if (!Directory.Exists(this.txtBackupFolder.Text))
                {
                    XtraMessageBox.Show("Kh\x00f4ng thể khởi tạo được thư mục d\x00f9ng để lưu trữ dữ liệu!", "Th\x00f4ng B\x00e1o");
                    return;
                }
            }
            SavePath(this.txtBackupFolder.Text);
            this.btnStart.Enabled = false;
            SYS_LOG.Insert("Cơ Sơ Dữ Liệu", "Sao Lưu", this.txtBackupFolder.Text + ", " + this.txtBackupFile.Text);
            DataController.ConnectString = SqlHelper.ConnectString;
            DataController backup = new DataController();
            this.lblMessage.Text = "Đang Sao Lưu...";
            backup.BackupProcess += new BackupProcessEventHander(this.BackupBackupProcess);
            backup.BackupComplete += new BackupCompleteEventHander(this.BackupBackupComplete);
            backup.BackupError += new BackupErrorEventHander(this.BackupBackupError);
            SqlHelper mySql = new SqlHelper(SqlHelper.ConnectString);
            mySql.Extract();
            new Thread(() => backup.BackupDataBase(mySql.Database, this.txtBackupFolder.Text + @"\" + this.txtBackupFile.Text)).Start();
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing && (this.components != null))
            {
                this.components.Dispose();
            }
            base.Dispose(disposing);
        }

        private void InitializeComponent()
        {
            ComponentResourceManager manager = new ComponentResourceManager(typeof(XfmBackupDatabase));
            SerializableAppearanceObject appearance = new SerializableAppearanceObject();
            this.lblMessage = new LabelControl();
            this.lblFileName = new LabelControl();
            this.txtBackupFile = new TextEdit();
            this.lblPath = new LabelControl();
            this.Bar = new ProgressBarControl();
            this.txtBackupFolder = new ButtonEdit();
            this.lblProgress = new LabelControl();
            this.cheOverwrite = new CheckEdit();
            this.btnHelp = new SimpleButton();
            this.btnClose = new SimpleButton();
            this.btnStart = new SimpleButton();
            this.pictureBox1 = new PictureBox();
            this.groupControl1 = new GroupControl();
            this.lblDetail = new LabelControl();
            this.txtBackupFile.Properties.BeginInit();
            this.Bar.Properties.BeginInit();
            this.txtBackupFolder.Properties.BeginInit();
            this.cheOverwrite.Properties.BeginInit();
            ((ISupportInitialize)this.pictureBox1).BeginInit();
            this.groupControl1.BeginInit();
            this.groupControl1.SuspendLayout();
            base.SuspendLayout();
            this.lblMessage.Appearance.Font = new Font("Tahoma", 9f, FontStyle.Bold, GraphicsUnit.Point, 0);
            this.lblMessage.Appearance.ForeColor = Color.SteelBlue;
            this.lblMessage.Appearance.Options.UseFont = true;
            this.lblMessage.Appearance.Options.UseForeColor = true;
            this.lblMessage.AutoSizeMode = LabelAutoSizeMode.Vertical;
            this.lblMessage.Location = new Point(0x88, 12);
            this.lblMessage.Name = "lblMessage";
            this.lblMessage.Size = new Size(0x151, 14);
            this.lblMessage.TabIndex = 0;
            this.lblMessage.Text = "Sao lưu dự ph\x00f2ng dữ liệu.";
            this.lblFileName.Location = new Point(5, 0x29);
            this.lblFileName.Name = "lblFileName";
            this.lblFileName.Size = new Size(0x34, 13);
            this.lblFileName.TabIndex = 1;
            this.lblFileName.Text = "T\x00ean tập tin";
            this.txtBackupFile.Location = new Point(0x43, 40);
            this.txtBackupFile.Name = "txtBackupFile";
            this.txtBackupFile.Size = new Size(0x142, 20);
            this.txtBackupFile.TabIndex = 2;
            this.lblPath.Location = new Point(5, 0x4a);
            this.lblPath.Name = "lblPath";
            this.lblPath.Size = new Size(0x36, 13);
            this.lblPath.TabIndex = 3;
            this.lblPath.Text = "Đường dẫn";
            this.Bar.Location = new Point(0x43, 11);
            this.Bar.Name = "Bar";
            this.Bar.Properties.ShowTitle = true;
            this.Bar.Size = new Size(0x142, 20);
            this.Bar.TabIndex = 6;
            this.txtBackupFolder.Location = new Point(0x43, 0x48);
            this.txtBackupFolder.Name = "txtBackupFolder";
            this.txtBackupFolder.Properties.Buttons.AddRange(new EditorButton[] { new EditorButton(ButtonPredefines.Glyph, "", -1, true, true, false, ImageLocation.MiddleCenter, (Image)manager.GetObject("txtBackupFolder.Properties.Buttons"), new KeyShortcut(System.Windows.Forms.Keys.None), appearance, "", "Browse", null, true) });
            this.txtBackupFolder.Properties.ButtonClick += new ButtonPressedEventHandler(this.TxtBackupFolderPropertiesButtonClick);
            this.txtBackupFolder.Size = new Size(0x142, 0x16);
            this.txtBackupFolder.TabIndex = 4;
            this.txtBackupFolder.TabStop = false;
            this.lblProgress.Location = new Point(5, 12);
            this.lblProgress.Name = "lblProgress";
            this.lblProgress.Size = new Size(0x2d, 13);
            this.lblProgress.TabIndex = 9;
            this.lblProgress.Text = "Tiến tr\x00ecnh";
            this.cheOverwrite.EditValue = true;
            this.cheOverwrite.Enabled = false;
            this.cheOverwrite.Location = new Point(0xd4, 0x141);
            this.cheOverwrite.Name = "cheOverwrite";
            this.cheOverwrite.Properties.Caption = "Ghi đ\x00e8 tập tin cũ";
            this.cheOverwrite.Size = new Size(0x85, 0x12);
            this.cheOverwrite.TabIndex = 10;
            this.btnHelp.Image = (Image)manager.GetObject("btnHelp.Image");
            this.btnHelp.Location = new Point(0x85, 0x13e);
            this.btnHelp.Name = "btnHelp";
            this.btnHelp.Size = new Size(0x49, 0x15);
            this.btnHelp.TabIndex = 0x1d;
            this.btnHelp.Text = "Trợ Gi\x00fap";
            this.btnClose.Image = (Image)manager.GetObject("btnClose.Image");
            this.btnClose.Location = new Point(0x1be, 0x13d);
            this.btnClose.Name = "btnClose";
            this.btnClose.Size = new Size(0x4b, 0x16);
            this.btnClose.TabIndex = 8;
            this.btnClose.Text = "Đ\x00f3ng";
            this.btnClose.Click += new EventHandler(this.BtnCloseClick);
            this.btnStart.Image = (Image)manager.GetObject("btnStart.Image");
            this.btnStart.Location = new Point(0x16d, 0x13d);
            this.btnStart.Name = "btnStart";
            this.btnStart.Size = new Size(0x4b, 0x16);
            this.btnStart.TabIndex = 7;
            this.btnStart.Text = "Thực Hiện";
            this.btnStart.Click += new EventHandler(this.BtnStartClick);
            this.pictureBox1.Dock = DockStyle.Left;
            this.pictureBox1.Image = Img.bg_backup;
            this.pictureBox1.Location = new Point(0, 0);
            this.pictureBox1.Name = "pictureBox1";
            this.pictureBox1.Size = new Size(0x7e, 0x15f);
            this.pictureBox1.TabIndex = 0x1f;
            this.pictureBox1.TabStop = false;
            this.groupControl1.Appearance.GradientMode = LinearGradientMode.ForwardDiagonal;
            this.groupControl1.AppearanceCaption.Font = new Font("Tahoma", 8.25f, FontStyle.Regular, GraphicsUnit.Point, 0);
            this.groupControl1.AppearanceCaption.ForeColor = Color.SteelBlue;
            this.groupControl1.AppearanceCaption.Options.UseFont = true;
            this.groupControl1.AppearanceCaption.Options.UseForeColor = true;
            this.groupControl1.AppearanceCaption.Options.UseTextOptions = true;
            this.groupControl1.AppearanceCaption.TextOptions.HAlignment = HorzAlignment.Center;
            this.groupControl1.BorderStyle = BorderStyles.NoBorder;
            this.groupControl1.Controls.Add(this.lblProgress);
            this.groupControl1.Controls.Add(this.txtBackupFolder);
            this.groupControl1.Controls.Add(this.lblFileName);
            this.groupControl1.Controls.Add(this.txtBackupFile);
            this.groupControl1.Controls.Add(this.lblPath);
            this.groupControl1.Controls.Add(this.Bar);
            this.groupControl1.Location = new Point(0x84, 90);
            this.groupControl1.Name = "groupControl1";
            this.groupControl1.ShowCaption = false;
            this.groupControl1.Size = new Size(0x189, 0x62);
            this.groupControl1.TabIndex = 0x20;
            this.groupControl1.Text = "Phục hồi dữ liệu đ\x00e3 được sao lưu";
            this.lblDetail.Appearance.Options.UseTextOptions = true;
            this.lblDetail.Appearance.TextOptions.WordWrap = WordWrap.Wrap;
            this.lblDetail.AutoSizeMode = LabelAutoSizeMode.None;
            this.lblDetail.Location = new Point(0x88, 0x20);
            this.lblDetail.Name = "lblDetail";
            this.lblDetail.Size = new Size(0x181, 0x20);
            this.lblDetail.TabIndex = 0x21;
            this.lblDetail.Text = "Mọi thứ sẽ rất tệ hại khi bạn kh\x00f4ng thể kh\x00f4i phục những dữ liệu n\x00e0y do chưa từng thực hiện sao lưu hệ thống.";
            base.AutoScaleDimensions = new SizeF(6f, 13f);
            base.AutoScaleMode = AutoScaleMode.Font;
            base.ClientSize = new Size(0x216, 0x15f);
            base.Controls.Add(this.lblDetail);
            base.Controls.Add(this.pictureBox1);
            base.Controls.Add(this.groupControl1);
            base.Controls.Add(this.btnHelp);
            base.Controls.Add(this.cheOverwrite);
            base.Controls.Add(this.btnClose);
            base.Controls.Add(this.btnStart);
            base.Controls.Add(this.lblMessage);
            base.FormBorderStyle = FormBorderStyle.FixedSingle;
            base.MaximizeBox = false;
            base.MinimizeBox = false;
            base.Name = "XfmBackupDatabase";
            base.ShowIcon = false;
            base.ShowInTaskbar = false;
            base.StartPosition = FormStartPosition.CenterScreen;
            this.Text = "Sao lưu dữ liệu";
            base.FormClosed += new FormClosedEventHandler(this.XfmBackupDatabase_FormClosed);
            this.txtBackupFile.Properties.EndInit();
            this.Bar.Properties.EndInit();
            this.txtBackupFolder.Properties.EndInit();
            this.cheOverwrite.Properties.EndInit();
            ((ISupportInitialize)this.pictureBox1).EndInit();
            this.groupControl1.EndInit();
            this.groupControl1.ResumeLayout(false);
            this.groupControl1.PerformLayout();
            base.ResumeLayout(false);
            base.PerformLayout();
        }

        private void InitMultiLanguages()
        {
            this.Text = MultiLanguages.GetString("tbl_DatabaseConfig", "BackupDatabase", "Sao Lưu Dữ Liệu");
            this.lblMessage.Text = MultiLanguages.GetString("tbl_DatabaseConfig", "BackupDatabaseTitle", "Sao lưu dự ph\x00f2ng dữ liệu");
            this.lblDetail.Text = MultiLanguages.GetString("tbl_DatabaseConfig", "BackupDatabaseDetail", "Mọi thứ sẽ rất tệ hại khi bạn kh\x00f4ng thể kh\x00f4i phục những dữ liệu n\x00e0y do chưa từng thực hiện sao lưu hệ thống.");
            this.lblProgress.Text = MultiLanguages.GetString("tbl_DatabaseConfig", "Progress", "Tiến tr\x00ecnh");
            this.lblFileName.Text = MultiLanguages.GetString("tbl_DatabaseConfig", "FileName", "T\x00ean tập tin");
            this.lblPath.Text = MultiLanguages.GetString("tbl_DatabaseConfig", "Path", "Đường dẫn");
            this.btnStart.Text = MultiLanguages.GetString("tbl_DatabaseConfig", "Action", "Thực Hiện");
            this.btnHelp.Text = MultiLanguages.GetString("tbl_DatabaseConfig", "Help", "Trợ Gi\x00fap");
            this.btnClose.Text = MultiLanguages.GetString("tbl_DatabaseConfig", "Close", "Đ\x00f3ng");
            this.cheOverwrite.Text = MultiLanguages.GetString("tbl_DatabaseConfig", "Overwrite", "Ghi đ\x00e8 tập tin cũ");
        }

        public static string LoadPath()
        {
            try
            {
                DataSet set = new DataSet();
                set.ReadXml(Application.StartupPath + @"\LayoutControl\xucBackup.xml");
                return set.Tables[0].Rows[0][0].ToString();
            }
            catch
            {
                return @"D:\Backup";
            }
        }

        protected override bool ProcessDialogKey(System.Windows.Forms.Keys keyData)
        {
            if (keyData == System.Windows.Forms.Keys.Escape)
            {
                base.Close();
                return true;
            }
            return false;
        }

        private void RaiseBackupCompleteEventHander(ServerMessageEventArgs e)
        {
            if (this.BackupComplete != null)
            {
                this.BackupComplete(this, e);
            }
        }

        private void RaiseBackupErrorEventHander(string message)
        {
            if (this.BackupError != null)
            {
                this.BackupError(this, message);
            }
        }

        private void RaiseBackupProcessEventHander(PercentCompleteEventArgs e)
        {
            if (this.BackupProcess != null)
            {
                this.BackupProcess(this, e);
            }
        }

        private void RaiseClosedHandler()
        {
            if (this.Closed != null)
            {
                this.Closed(this);
            }
        }

        public static void SavePath(string Path)
        {
            DataSet set = new DataSet();
            using (DataTable table = new DataTable())
            {
                table.Columns.Add("Path", typeof(string));
                object[] objArray = new object[] { Path };
                table.Rows.Add(new object[0]);
                table.Rows[0][0] = objArray[0];
                set.Tables.Add(table);
            }
            try
            {
                set.WriteXml(Application.StartupPath + @"\LayoutControl\xucBackup.xml");
            }
            catch
            {
            }
        }

        private void txtBackupFile_Properties_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
        }

        private void TxtBackupFolderPropertiesButtonClick(object sender, ButtonPressedEventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                this.txtBackupFolder.Text = dialog.SelectedPath;
            }
        }

        private void XfmBackupDatabase_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.RaiseClosedHandler();
        }

        public delegate void ClosedHandler(object sender);
    }

}
